/**
 * Copyright(c) 2013 Jade Techonologies Co., Ltd.
 *
 * History:
 *   13-7-12 上午10:39 Created by sky
 */
package com.jade.modules.message.common;

import java.io.*;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import com.jade.framework.base.util.DataUtils;

/**
 * 统一状态码和协议状态的映射。
 *
 * @author sky
 * @version 1.0 13-7-12 上午10:39
 */
public class StatusMapper
{
    private static final String PROTOCOL_PREFIX = "protocol";
    // status mapper.
    protected Map<Integer, Integer> statusMap = new HashMap<Integer, Integer>();
    // reverse status mapper
    protected Map<Integer, Integer> reverseStatusMap = new HashMap<Integer, Integer>();

    public void load(String mappingResource)
            throws IOException
    {
        Properties props = new Properties();
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(mappingResource);
            BufferedReader reader = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
            props.load(reader);
        }
        catch (IOException ioe) {
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            InputStream is = loader.getResourceAsStream(mappingResource);
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            props.load(reader);
        }


        Enumeration en = props.propertyNames();
        while (en.hasMoreElements()) {
            String leftName = (String) en.nextElement();
            String rightName = props.getProperty(leftName);
            leftName = leftName.trim();
            rightName = rightName.trim();

            if (leftName.startsWith(PROTOCOL_PREFIX)) {
                //protocol.
                leftName = leftName.substring(PROTOCOL_PREFIX.length() + 1);
                int protocolStatus = DataUtils.getInt(leftName, -1);
                int status = DataUtils.getInt(rightName, -1);
                if (protocolStatus >= 0 && status >= 0) {
                    reverseStatusMap.put(protocolStatus, status);
                }
            }
            else {
                int status = DataUtils.getInt(leftName, -1);
                int protocolStatus = DataUtils.getInt(rightName, -1);
                if (protocolStatus >= 0 && status >= 0) {
                    statusMap.put(status, protocolStatus);
                }
            }
        }
    }

    public int getProtocolStatus(int status)
    {
        if (reverseStatusMap.containsKey(status)) {
            return reverseStatusMap.get(status);
        }
        else {
            return reverseStatusMap.get(MessageStatus.SC_SERVER_ERROR);
        }
    }

    public int getStatus(int protocolStatus)
    {
        if (statusMap.containsKey(protocolStatus)) {
            return statusMap.get(protocolStatus);
        }
        else {
            return MessageStatus.SC_SERVER_ERROR;
        }
    }
}